package org.nabc.generate.view;

import lombok.extern.slf4j.Slf4j;
import org.nabc.configuration.FileConfiguration;
import org.nabc.constant.ModeConstant;
import org.nabc.constant.TypeConstant;
import org.nabc.generate.AbstractRunnableTask;
import org.nabc.support.PropertyValue;
import org.nabc.support.PropertyValues;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class VueViewTemplateGenerate extends AbstractRunnableTask {
    @Override
    public void setParameters(FileConfiguration fileConfiguration, PropertyValues propertyValues) {
        this.fileSuffix = "vue";
        fileTemplateData = inputFromFile("src/main/resources/template/vue/view/Vue.template");
        super.setParameters(fileConfiguration, propertyValues, "vue");
    }

    @Override
    public void setModelAndType() {
        this.type = TypeConstant.VIEW;
        this.mode = ModeConstant.VUE;
    }

    @Override
    public void generate() throws IOException {
        String entityName = lowerLetter(this.entityName);

        String[] strings = getTemplate("#\\[[\\W*\\w*]{0,}?\\]#", fileTemplateData.toString());

        Map<String, String> completeStringMap = new HashMap<>();
        for (String str : strings) {
            String temp = dealTemplate(str, entityName, propertyValues);
            completeStringMap.put(str, temp);
        }

        String vueFileData = fileTemplateData.toString();

        for (String key : completeStringMap.keySet()) {
            vueFileData = vueFileData.replace("#[" + key + "]#", completeStringMap.get(key));
        }

        vueFileData = vueFileData
                .replace("#{entityClass}", entityName)
                .replace("#{entityName}", entityName);

        outputToFile(vueFileData, filePath);
    }

    /**
     * 处理模板
     */
    private String dealTemplate(String template, String entityName, PropertyValues propertyValues) {
        StringBuffer stringBuffer = new StringBuffer();

        for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
            stringBuffer.append(template
                    .replace("#{columnComment}", getComment(propertyValue))
                    .replace("#{columnName}", propertyValue.getColumnName())
                    .replace("#{entityName}", entityName)).append("\n");
        }

        return stringBuffer.toString();
    }

    private String getComment(PropertyValue propertyValue) {
        return propertyValue.getColumnComment() == null || propertyValue.getColumnComment().equals("") ?
                propertyValue.getColumnName() : propertyValue.getColumnComment();
    }
}
